package com.zhaoguang.car.manager;

import com.zhaoguang.car.entity.UserToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

@Component
public class TokenManager {

    @Autowired
    private CacheManager cacheManager;

    /**
     * 生成Token
     */
    public String createToken() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    /**
     * 缓存Token
     */
    public boolean cacheToken(int userId, String token) {
        //缓存
        boolean result = cacheManager.set("car.user." + userId + ".token", token, 1L);

        return result;
    }

    /**
     * 删除Token
     *
     * @param userId
     */
    public boolean deleteToken(int userId) {
        Boolean result = cacheManager.remove("car.user." + userId + ".token");

        return result;
    }

    /**
     * 检查Token是否正确
     */
    public boolean checkToken(int userId, String token) {
        boolean result = false;
        String tokenInCache = cacheManager.get("car.user." + userId + ".token");
        if (tokenInCache == null) {
            return result = false;
        }
        if (tokenInCache.equals(token)) {
            result = true;
        }
        return result;
    }
}
